using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace FeedFly
{
    /// <summary>
    /// Form for adding new folders. 
    /// </summary>
    public partial class AddFolderForm : Form, FolderBrowseInterface
    {
        private int parentId;

        public AddFolderForm()
        {
            InitializeComponent();
        }

        public void PrepareForm(int folderId, string breadCrumbs)
        {
            this.parentId = folderId;
            this.BreadCrumbLabel.Text = breadCrumbs;
            this.NameTextBox.Text = String.Empty;
            this.errorLabel.Text = String.Empty;
        }

        public void FolderChosen(int folderId, string folderName, string breadCrumbs)
        {
            if (parentId != folderId)
            {
                parentId = folderId;
                this.BreadCrumbLabel.Text = breadCrumbs;
                errorLabel.Text = String.Empty;
            }
        }

        private void cancelMenuItem_Click(object sender, EventArgs e)
        {
            Screens.Main.Show();
            Hide();
        }

        private void createFolderMenuItem_Click(object sender, EventArgs e)
        {                       
            // Check if folder exists if it doesn't then create folder
            StringBuilder sql = new StringBuilder("SELECT 1 from Folder WHERE Name = '", 100);
            sql.Append(NameTextBox.Text).Append("' and ParentId = '");
            sql.Append(parentId.ToString()).Append("'");

            if (Data.ExecuteScalar(sql.ToString()) == null)
            {
                Folder.Create(NameTextBox.Text, this.parentId);

                // add new folder to list if parent is open
                Screens.Main.RefreshFolder(this.parentId);
                Screens.Main.Show();
                Hide();
            }
            else
                this.errorLabel.Text = "Folder already exists!";

        }

        private void ChangeParent(object sender, EventArgs e)
        {
            Screens.SelectFolder.PrepareForm(this);
            Screens.SelectFolder.Show();
            Hide();
        }

        private void errorLabel_TextChanged(object sender, EventArgs e)
        {
            errorLabel.Visible = (errorLabel.Text.Length > 0);
        }

        private void NameTextBox_TextChanged(object sender, EventArgs e)
        {
            errorLabel.Text = String.Empty;
        }

    }
}